package org.autocode.code.template;

import freemarker.cache.ByteArrayTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.autocode.code.ColumnInfo;
import org.autocode.code.TableInfo;
import org.autocode.util.DateUtils;
import org.autocode.util.JavaUtils;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: autocode
 * @description:
 * @author: zhu.xiaojie
 * @create: 2020-08-23 09:03
 */
public class TemplateHelper {

    private final Configuration configuration;

    private TemplateHelper(){
        this.configuration = new Configuration(Configuration.VERSION_2_3_29);
        this.configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
        this.configuration.setClassForTemplateLoading(this.getClass() , "/template");
    }


    private static final TemplateHelper INSTANCE = new TemplateHelper();
    public static TemplateHelper getInstance(){
        return INSTANCE;
    }


    /**
     * 生成 dao 层的代码
     * @return
     */
    public String genDaoCode(TableInfo tableInfo, ColumnInfo primaryColumn)  {
        String className = tableInfo.getClassName();
        String primaryName = primaryColumn.getColumnName();

        StringWriter stringWriter = null;
        try {
            Template template = configuration.getTemplate("Dao.ftl");

            String toJavaClassName = JavaUtils.toJavaClassName(className);

            Map<String , Object> data = new HashMap<>();
            data.put("tableName" , tableInfo.getTableName());
            data.put("daoName" ,  toJavaClassName + "Dao");
            data.put("dateTime" , DateUtils.format(new Date()));
            data.put("poName" , toJavaClassName);
            data.put("poVar" , JavaUtils.toJavaFieldName(toJavaClassName));
            data.put("primaryNameLow" , JavaUtils.toJavaFieldName(primaryName));
            data.put("primaryNameUpper" , JavaUtils.toJavaClassName(primaryName));
            data.put("primaryTypeName" , primaryColumn.getJavaType().getName());
            data.put("primaryColumnName" , primaryColumn.getColumnName());
            data.put("primaryColumnComment" , primaryColumn.getColumnComment());



            stringWriter = new StringWriter();
            template.process(data , stringWriter);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return stringWriter.toString();
    }
}
